import React from 'react'
import PropTypes from 'prop-types'
import {routerRedux} from 'dva/router'
import {connect} from 'dva'
import {Button, Col, Form, Layout, message, Popconfirm, Row, Select, Tabs} from 'antd'
import {Page} from 'components'
import queryString from 'query-string'
import Filter from './components/Filter'
import RoleMenu from './components/RoleMenu'
import ButtonList from './components/ButtonList'
import DataList from "./components/DataList"
import MemberList from "./components/MemberList"
import MemberModal from "./components/MemberModal"
import Modals from "./components/Modals"
import {queryArray, treeToArray} from "utils"

const {Sider, Content} = Layout
const {TabPane} = Tabs
const FormItem = Form.Item

class Permission extends React.Component {

  constructor () {
    super()

    this.state = {
      activeKey: "modals",
    }
  }

  handlePermsChange (dispatch, roleId, key, menuId) {
    dispatch({
      type: 'permission/dataAuthorize',
      payload: {
        roleId: roleId,
        menuId: menuId,
        key,
      },
    }).then(() => {
      message.success("授权成功")
    })
  }

  render () {
    const {location, dispatch, permission, employee, loading} = this.props
    const {query, pathname} = location
    const {list, roles, modals, buttons, data, pagination, selectedRowKeys, expandedRowKeys, memberSelectedKeys, selectedRoleId, memberModalVisible} = permission
    const {list: employeeList, selectedRowKeys: employeeSelectedRowKeys, pagination: employeePagination} = employee
    const {activeKey} = this.state

    const handleRefresh = (newQuery) => {
      dispatch(routerRedux.push({
        pathname,
        search: queryString.stringify({
          ...query,
          ...newQuery,
        }),
      }))
    }

    const handleRefreshByType = (type, newQuery) => {
      dispatch({
        type: `permission/${type}`,
        payload: {
          ...newQuery,
        },
      })
    }

    const handleMemberRefresh = (newQuery) => {
      const {roleId} = newQuery
      dispatch({
        type: 'employee/query',
        payload: {
          ...newQuery,
        },
      }).then(() => {
        dispatch({
          type: 'permission/updateState',
          payload: {
            selectedRoleId: roleId,
          },
        })
      })
    }

    const handleNoRoleMemberRefresh = (newQuery) => {
      dispatch({
        type: 'permission/noRoleMembers',
        payload: {
          ...newQuery,
          hasRoleId: 0,
        },
      })
    }

    const getCurrent = () => {
      return (employeeList.length === employeeSelectedRowKeys.length && employeePagination.current > 1) ? employeePagination.current - 1 : employeePagination.current
    }

    const handleTabChange = (key) => {
      this.setState({
        activeKey: key,
      })

      if (key === 'modals') {
        return
      } else if (key === 'members') {
        handleMemberRefresh({
          current: getCurrent(),
          roleId: selectedRoleId,
        })
      } else {
        handleRefreshByType(key, {roleId: selectedRoleId})
      }
    }

    const modalsProps = {
      rowKey: 'id',
      dataSource: modals,
      loading: loading.effects['permission/getModals'],
      pagination: false,
      location,
      expandedRowKeys,
      onExpand (expanded, record) {
        dispatch({
          type: 'permission/changeExpand',
          payload: {
            expanded,
            key: record.id,
          },
        })
      },
      rowSelection: {
        selectedRowKeys,
        onChange: (keys) => {
          dispatch({
            type: 'permission/updateState',
            payload: {
              selectedRowKeys: keys,
            },
          })
        },
      },
    }

    const buttonListProps = {
      location,
      loading,
      buttons,
      handleClick (item) {
        dispatch({
          type: 'permission/buttonAuthorize',
          payload: {
            roleId: selectedRoleId,
            btnId: item.id,
            type: item.authorized ? 'delete' : 'grant',
          },
        }).then(() => {
          message.success("授权成功")
        })
      },
    }

    const dataListProps = {
      location,
      loading,
      data,
      handleChange: (key, menuId) => {
        this.handlePermsChange(dispatch, selectedRoleId, key, menuId)
      }
    }

    const memberListProps = {
      rowKey: 'id',
      dataSource: employeeList,
      pagination: employeePagination,
      onChange (page) {
        handleMemberRefresh({
          current: page.current,
          size: page.pageSize,
          roleId: selectedRoleId,
        })
      },
      loading: loading.effects['employee/query'],
      rowSelection: {
        employeeSelectedRowKeys,
        onChange: (keys) => {
          dispatch({
            type: 'employee/updateState',
            payload: {
              selectedRowKeys: keys,
            },
          })
        },
      },
    }

    const filterProps = {
      filter: {
        ...query,
      },
      handleReset () {
        handleRefresh()
        message.success("刷新成功")
      },
      onAuthorize () {
        selectedRowKeys.map(_ => {
          const modalArray = []
          treeToArray(modals, modalArray)
          const item = queryArray(modalArray, _, 'id')
          if (item && item.mpid && selectedRowKeys.indexOf(item.mpid) < 0) {
            selectedRowKeys.push(item.mpid)
          }
        })
        dispatch({
          type: 'permission/modalAuthorize',
          payload: {
            roleId: selectedRoleId,
            menuIds: selectedRowKeys,
          },
        }).then(() => {
          message.success("授权成功")
        })
      },
    }

    const roleMenuProps = {
      roles,
      selectedRoleId,
      handleRoleMenuClick (item) {
        dispatch({
          type: 'updateState',
          payload: {
            selectedRoleId: item.id,
          },
        })
        switch (activeKey) {
          case 'modals':
            handleRefresh({roleId: item.id})
            break
          case 'buttons':
          case 'datas':
            handleRefreshByType(activeKey, {roleId: item.id})
            break
          default:
            handleMemberRefresh({current: getCurrent(), roleId: item.id})
            break
        }
      },
    }

    const modalMemberListProps = {
      pagination,
      dataSource: list,
      onChange (page) {
        handleNoRoleMemberRefresh({
          ...query,
          current: page.current,
          size: page.pageSize,
        })
      },
      rowSelection: {
        memberSelectedKeys,
        onChange: (keys) => {
          dispatch({
            type: 'permission/updateState',
            payload: {
              memberSelectedKeys: keys,
            },
          })
        },
      },
    }

    const memberModalProps = {
      visible: memberModalVisible,
      filter: {
        ...query,
      },
      width: 1000,
      maskClosable: false,
      confirmLoading: loading.effects['permission/noRoleMembers'],
      title: '添加成员',
      wrapClassName: 'vertical-center-modal',
      onFilterChange (fields) {
        handleNoRoleMemberRefresh({...fields, current: 1})
      },
      onOk () {
        dispatch({
          type: 'permission/addMembers',
          payload: {
            roleId: selectedRoleId,
            empIds: memberSelectedKeys,
          },
        }).then(() => {
          message.success("添加成员成功")
          handleMemberRefresh({current: 1, roleId: selectedRoleId})
          dispatch({
            type: 'permission/getRoles',
          })
          dispatch({
            type: 'permission/hideMemberModal',
          })
        })
      },
      onCancel () {
        dispatch({
          type: 'permission/hideMemberModal',
        })
      },
      modalMemberListProps,
    }

    const onAddMember = () => {
      handleNoRoleMemberRefresh({current: 1})
      dispatch({
        type: 'permission/showMemberModal',
      })
    }

    const handleDeleteMember = () => {
      dispatch({
        type: 'permission/deleteMembers',
        payload: {
          roleId: selectedRoleId,
          empIds: employeeSelectedRowKeys,
        },
      }).then(() => {
        message.success("删除成员成功")
        handleMemberRefresh({current: getCurrent(), roleId: selectedRoleId})
        dispatch({
          type: 'permission/getRoles',
        })
      })
    }

    const ColProps = {
      xs: 24,
      sm: 12,
      style: {
        marginBottom: 16,
      },
    }

    return (
      <Layout>
        <Sider width={240} style={{background: '#ffffff'}}>
          <RoleMenu {...roleMenuProps}/>
        </Sider>
        <Content style={{padding: '0 24px', minHeight: 280}}>
          <Page inner>
            <Tabs activeKey={activeKey} onChange={handleTabChange}>
              <TabPane tab={'模块权限'} key={'modals'}>
                <Filter {...filterProps}/>
                <Modals {...modalsProps} />
              </TabPane>
              <TabPane tab={'按钮权限'} key={'buttons'}>
                <ButtonList {...buttonListProps}/>
              </TabPane>
              <TabPane tab={'数据权限'} key={'datas'}>
                <Row gutter={24}>
                  <Col {...ColProps} xl={{span: 24}} md={{span: 24}} sm={{span: 24}}>
                    <FormItem labelCol={{span: 2}} style={{bottom: 0}} wrapperCol={{span: 5}} label="分配所有">
                      <Select allowClear
                              onChange={(val) => {
                                this.handlePermsChange(dispatch, selectedRoleId, val)
                              }}
                              placeholder="请选择权限" style={{width: '100%'}}>
                        {data.keys
                          ? data.keys.map(item => (<Option value={item.key}>{item.text}</Option>))
                          : ""}
                      </Select>
                    </FormItem>
                  </Col>
                </Row>
                <DataList {...dataListProps}/>
              </TabPane>
              <TabPane tab={'角色成员'} key={'members'}>
                <Row gutter={24}>
                  <Col {...ColProps} xl={{span: 24}} md={{span: 24}} sm={{span: 24}}>
                    <div className="flex-vertical-center" style={{float: 'left'}}>
                      <Button type="primary" onClick={onAddMember}>添加成员</Button>
                      {
                        employeeSelectedRowKeys.length > 0 &&
                        <div>
                          <Popconfirm title="确定要删除这些数据吗?" placement="top" onConfirm={handleDeleteMember}>
                            <Button className="margin-right" type="danger" style={{marginLeft: 8}}>删除</Button>
                          </Popconfirm>
                          {`选中了 ${employeeSelectedRowKeys.length} 条数据`}
                        </div>
                      }
                    </div>
                  </Col>
                </Row>
                <MemberList {...memberListProps}/>
                {memberModalVisible && <MemberModal {...memberModalProps}/>}
              </TabPane>
            </Tabs>
          </Page>
        </Content>
      </Layout>
    )
  }
}

Permission.propTypes = {
  permission: PropTypes.object,
  location: PropTypes.object,
  dispatch: PropTypes.func,
  loading: PropTypes.object,
}

export default connect(({permission, employee, loading}) => ({employee, permission, loading}))(Permission)
